package yxy.game.pm2.command.wuchao;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.wuchao.WuchaoHandle;
import yxy.game.pm2.module.wuchao.WuchaoModule;

/** 乌巢 乌巢挑战 */
@MessageType(proto = Command.WuchaoChanllenge, classtype = WuchaoMessage.WuchaoChanllengeRequest.class)
public class CMD_WuchaoChanllenge extends Command<WuchaoMessage.WuchaoChanllengeRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoChanllengeRequest request) {
		String playerCode = messageSource.getTag();
		String eventCode = request.getCode();
		String heroCode = request.getHero();

		WuchaoMessage.WuchaoChanllengeResponse.Builder response = WuchaoMessage.WuchaoChanllengeResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		try {
			if (wuchaoModule.tryLock()) {
				Result result = new WuchaoHandle().battleResponseExecute(wuchaoModule, eventCode, heroCode, response);
				send(messageSource, response, result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoChanllengeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}